import axios from 'axios'
import qs from 'qs'
const Base64 = require('js-base64')
const Cryptojs = require('crypto-js')
const baseUrl = require('@/utils/config')['default'].baseUrl //引用基础地址
const appInfo = require('@/utils/config')['default'].appInfo //引用基础地址
import { decrypt } from './interface-encryption'
import Vue from 'vue'
import { Toast } from 'vant';
import md5 from "crypto-js/md5";
Vue.use(Toast);

let isEncrypt = true

axios.defaults.timeout = 100000
axios.defaults.headers.post['Content-Type'] = 'application/json'
//允许跨域
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.crossDomain = true
axios.defaults.withCredentials = true

// apptoken生成函数
function addAppToken(app) {
  // 0212 加密账号
  const appId = app.appId // 应用id
  const secret = app.secret // MnVkNmY5ZmJnOXoxc2RmaGd1ZWdoZnQyeGZtcHFzZGs=
  const key = app.key // ZHd6NDE0cnl0NzQxc3Bxcw==
  const jetLag = 0 // 服务器与本机时间差
  let timestamp = new Date().getTime()
  timestamp += Number(jetLag)
  const bs6 = Base64.Base64.encode(' {"appId":"' + appId + '","timestamp":' + timestamp + '}')
  const h256 = Cryptojs.HmacSHA256(secret + '.' + timestamp, key).toString()
  return bs6 + '.' + h256
}

// 添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
  (config) => {
    config.headers.accessToken = localStorage.getItem('accessToken') || ''
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应
axios.interceptors.response.use(
  (response) => {
    // 加解密判断
    let res = isEncrypt ? decrypt(response.data, response.config.key, response.config.iv) : response.data
    return res
  },
  (error) => {
    if (!error.response) {
      Toast(error.message)
    }
    return Promise.reject(error.response.data) // 返回接口返回的错误信息
  }
)

// 请求调用函数
function processRequest(method, url, options) {
  //获取apptoken
  let appToken = ''
  let data = ''
  appToken = addAppToken(appInfo)
  url = method == 'get' ? url + '?' + qs.stringify(options.params) : url
  data = options.data ? options.data : ''

  // axios请求
  let axiosParams = {
    baseURL: baseUrl,
    url,
    method,
    headers: { appToken },
    data,
    key: appInfo.key,
    iv: appInfo.iv
  }
  return axios(axiosParams)
    .then((res) => {
      return res
    })
    .catch((res) => {
      return Promise.reject(res)
    })
}
//加head
function processRequestSign(method, url, options,sign,timstamp) {
  //获取apptoken
  let appToken = ''
  let data = ''
  appToken = addAppToken(appInfo)
  url = method == 'get' ? url + '?' + qs.stringify(options.params) : url
  data = options.data ? options.data : ''

  // axios请求
  let axiosParams = {
    baseURL: baseUrl,
    url,
    method,
    headers: { appToken,
      'UHCC_SIGN': sign,
      'UHCC_TIMESTAMP': timstamp },
    data,
    key: appInfo.key,
    iv: appInfo.iv
  }
  return axios(axiosParams)
      .then((res) => {
        return res
      })
      .catch((res) => {
        return Promise.reject(res)
      })
}

export default {
  get(url, params, urlType) {
    return processRequest('get', url, { params }, urlType)
  },
  post(url, data = '', urlType) {
    return processRequest('post', url, { data }, urlType)
  },
  getWithSign(url, params, urlType,sign,timstamp) {
    return processRequestSign('get', url, { params }, urlType,sign,timstamp)
  },
  Do(body,pathname,timestamp) {

    // const url = new URL(
    //     'http://localhost:1919/assets/testQuerySign?param2=2&param1=1&parama=0'
    // )
    const key = '083b83b0ed1c4d73'

    const signContent = md5(JSON.stringify(body))
    // const { search, pathname } = url
    // const array = search
    //     .substring(1)
    //     .split('&')
    //     .sort((a, b) => {
    //       const [k1, v1] = a.split('=')
    //       const [k2, v2] = b.split('=')
    //       if (k1.toLowerCase() < k2.toLowerCase()) {
    //         return -1
    //       }
    //       if (k1.toLowerCase() > k2.toLowerCase()) {
    //         return 1
    //       }
    //       return 0
    //     })
    console.log(
        `${signContent}&&${pathname}&${timestamp}&${key}`
    )
  },
}
